package com.example.touristassist;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.SmackAndroid;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import com.example.touristassist.R;
import com.example.xmppcore.XMPPLogic;

import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	EditText uname;
	EditText upass;
	Button b1;
	int users_id;
	private XMPPConnection mXmppConnection;
	private ConnectionConfiguration mConnectionConfiguration;
	private boolean autoLogIn;
	private boolean setAutoLogin = false;
	
	private static final int SETTING = 1;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        uname = (EditText)findViewById(R.id.txt_username);
        upass = (EditText)findViewById(R.id.txt_password);
        b1 = (Button)findViewById(R.id.btn_login); 
        resetUI();
        
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);	
        autoLogIn = prefs.getBoolean(AppConfig.AUTO_LOGIN, false);
        if(autoLogIn)
        	new ConnectToXMPPServer().execute();
        
    }
    
    void resetUI() {
    	upass.setText("");
    	if (uname.getText().length() > 0)
    		upass.requestFocus();
    	else
    		uname.requestFocus();
    }
    
    public void onClick(View v) {
    	new ConnectToXMPPServer().execute();
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.action_settings:	
			Intent intent = new Intent(this, SettingActivity.class);
	    	startActivityForResult(intent, SETTING);
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode) {
			case SETTING:
				settingReturn(resultCode, data);
				break;
		}
		
		//displayPref();
	}
		
	private void settingReturn(int resultCode, Intent data){
		if(resultCode == Activity.RESULT_OK)
		{
			Toast.makeText(this, data.getStringExtra(AppConfig.SETTING_RESULT), Toast.LENGTH_LONG).show();
		}
	}
	
	private boolean connectToServer()
	{
		boolean isLogInSuccess = false;
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);	
		String host = prefs.getString(AppConfig.HOST_PREF, "0");
		int port = prefs.getInt(AppConfig.PORT_PREF, 0);
		String service = prefs.getString(AppConfig.SERVICE_PREF, "0");
		
		try
		{
			SmackConfiguration.setPacketReplyTimeout(15000);
			SmackAndroid.init(getBaseContext());
			mConnectionConfiguration = new ConnectionConfiguration(host, port, service);
			mConnectionConfiguration.setRosterLoadedAtLogin(false);
			mXmppConnection = new XMPPConnection(mConnectionConfiguration);
			mConnectionConfiguration.setSASLAuthenticationEnabled(true);
			SASLAuthentication.supportSASLMechanism("PLAIN", 0);
			mXmppConnection.connect();
			
			if(autoLogIn){
				String userName = prefs.getString(AppConfig.USER_NANE, "0");
				String password = prefs.getString(AppConfig.PASSWORD, "0");
				isLogInSuccess = verifyUser(userName, password);
			}
			else{
				isLogInSuccess = verifyUser(uname.getText().toString(), upass.getText().toString());
				if(setAutoLogin){
					this.getPreferences(MODE_PRIVATE).edit().putString(AppConfig.USER_NANE,uname.getText().toString());
					this.getPreferences(MODE_PRIVATE).edit().putString(AppConfig.PASSWORD,upass.getText().toString());
					this.getPreferences(MODE_PRIVATE).edit().putBoolean(AppConfig.AUTO_LOGIN, true);
				}
			}

		}
		catch(XMPPException e)
    	{
    		Log.e("XMPPConnection", e.getMessage());	
    		
    	}
		catch(Exception e)
		{
			Log.e("XMPPConnection", e.getMessage());
		}
		return isLogInSuccess;
	}
	
	private boolean verifyUser(String username, String password) {
		 try{
	    	mXmppConnection.login(username, password);
			// Set the status to available
			Presence presence = new Presence(Presence.Type.available);
			mXmppConnection.sendPacket(presence);
	    	return true;
	    }
		catch(XMPPException e)
    	{
    		Log.e("XMPPConnection", e.getMessage());	
 
    	}
		catch(Exception e)
		{
			Log.e("XMPPConnection", e.getMessage());
		}
		 return false;
	}	 
	
	class ConnectToXMPPServer extends AsyncTask<Void, Void, Boolean>{
		 @Override
			protected void onPreExecute() {
				super.onPreExecute();
			}
	    	
	    	@Override
			protected Boolean doInBackground(Void... arg0) {
	    	
	    		return connectToServer();
	    	}
	    	
	    	@Override
			protected void onProgressUpdate(Void... values) {
				
			}
			
			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				if(result.booleanValue())
				{
					//Singleton pattern store connection
					XMPPLogic.getInstance().setConnection(mXmppConnection);
					//Goto GroupList activity
					Intent intent = new Intent(MainActivity.this, MenuActivity.class);
		            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
		            getApplicationContext().startActivity(intent);
				}
				else {
					//Fail
					Toast.makeText(MainActivity.this, R.string.main_login_fail, Toast.LENGTH_LONG).show();
				}
			}
	 }
}
